package com.demon.activitychange.net.impl;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.demon.activitychange.net.Callback;
import com.demon.activitychange.net.IApiMgr;
import com.demon.activitychange.persist.IPersist;
import com.demon.activitychange.persist.PersistKey;
import com.demon.activitychange.util.JSONObjectPack;
import com.demon.activitychange.util.TraceUtil;
import com.demon.activitychange.xposed.HookMain.DyOperEnum;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.HttpException;

class ApiMgr implements IApiMgr {
    private static final String NO_DATA = "no data";
    private static final String PARSE_ERROR = "parse error";
    private static final String REQUEST_ERROR = "request error";
    private static final String REQUEST_CANCEL = "request cancel";

    private IPersist mPersistence;
    private String mDomain;

    ApiMgr(IPersist persist) {
        mPersistence = persist;
    }

    @Override
    public boolean uploadResult(String cmd, JSONObject data, @NonNull Callback<String> callback) {
        String url = "";
        mDomain = (String) mPersistence.readData(PersistKey.DOMAIN, "");
        if (DyOperEnum.login.toString().equals(cmd)) {
            url = ApiUrl.loginResult(mDomain);
        } else if (DyOperEnum.loginVerify.toString().equals(cmd)) {
            url = ApiUrl.loginVerifyResult(mDomain);
        } else if (DyOperEnum.sendCode.toString().equals(cmd)) {
            url = ApiUrl.sendCodeResult(mDomain);
        } else if (DyOperEnum.smsLogin.toString().equals(cmd)) {
            url = ApiUrl.smsLoginResult(mDomain);
        } else if (DyOperEnum.smsReg.toString().equals(cmd)) {
            url = ApiUrl.smsRegResult(mDomain);
        } else if (DyOperEnum.smsUpdatePassword.toString().equals(cmd)) {
            url = ApiUrl.smsUpdatePasswordResult(mDomain);
        } else if (DyOperEnum.message.toString().equals(cmd)) {
            url = ApiUrl.messageResult(mDomain);
        } else if (DyOperEnum.exit.toString().equals(cmd)) {
            url = ApiUrl.exitResult(mDomain);
        }
        if (TextUtils.isEmpty(url)) {
            return false;
        }

        // WebSocketMgr.getInstance().sendCmd(cmd, data);
        JSONObject obj = new JSONObjectPack()
                .putValue("data", data)
                .getJSONObject();
        XUtil.postJson(url, "", obj, new ApiCallback(new Callback<Object>() {
            @Override
            public void onSuccess(Object data) {
                if (callback != null) {
                    callback.onSuccess("");
                }
            }

            @Override
            public void onFailure(String errMsg) {
                if (callback != null) {
                    callback.onFailure(errMsg);
                }
            }
        }));
        return true;
    }

    private class ApiCallback implements org.xutils.common.Callback.CommonCallback<String> {
        private Callback<Object> mCallback;

        ApiCallback(Callback<Object> callback) {
            this.mCallback = callback;
        }

        @Override
        public void onSuccess(String result) {
            boolean isResult = false;
            String errMsg = NO_DATA;

            try {
                TraceUtil.d("result = " + result);
                JSONObject obj = new JSONObject(result);
                int code = obj.optInt("code");
                if (code == 200) {
                    isResult = true;
                    // JSONObject data = obj.optJSONObject("data");
                    // 这里不能用optJSONObject，因为获取到的可能是JSONObject、也可能是JSONArray
                    Object data = obj.opt("data");
                    mCallback.onSuccess(data);
                } else {
                    String msg = obj.optString("msg");
                    if (msg != null) {
                        errMsg = msg;
                    }
                }
            } catch (JSONException e) {
                errMsg = PARSE_ERROR;
                e.printStackTrace();
            }

            if (!isResult) {
                mCallback.onFailure(errMsg);
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (ex instanceof HttpException) {
                mCallback.onFailure(ex == null ? REQUEST_ERROR : ((HttpException) ex).getResult());
                return;
            }

            mCallback.onFailure(ex == null ? REQUEST_ERROR : ex.getMessage());
        }

        @Override
        public void onCancelled(CancelledException cex) {
            mCallback.onFailure(REQUEST_CANCEL);
        }

        @Override
        public void onFinished() {

        }
    }
}

